package com.msb.configconsumer.ext;

import org.aopalliance.aop.Advice;
import org.springframework.amqp.rabbit.config.AbstractRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @author DreamAndLove
 * @date 2024/09/09 9:30
 * @description
 */
@Component
@Order(1)
public class SleuthFixedPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        if(bean instanceof SimpleRabbitListenerContainerFactory) {
            SimpleRabbitListenerContainerFactory factory = (SimpleRabbitListenerContainerFactory) bean;
            Class<? extends SimpleRabbitListenerContainerFactory> aClass = factory.getClass();
            try {
                Class<AbstractRabbitListenerContainerFactory> superclass = (Class<AbstractRabbitListenerContainerFactory>) aClass.getSuperclass();
                Field adviceChain = superclass.getDeclaredField("adviceChain");
                adviceChain.setAccessible(true);
                Object o = adviceChain.get(factory);
                if (o == null){
                    factory.setAdviceChain(new Advice[]{});
                }
            } catch (NoSuchFieldException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            return factory;
        }
        return bean;
    }
}
